from applications.utils.udp_discovery import UDPDiscoveryServer
import logging
from applications.extensions.init_websocket import publish_msg
import json

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('UDPDiscovery')
current_app = None


def on_client_found(client_info, from_address):
    # logger.info(f"found client: {client_info['name']} (IP: {client_info['ip']}) from {from_address}")
    # logger.info(f"服务器发现客户端: {client_info['name']} (IP: {client_info['ip']}) 来自 {from_address}")
    # logger.info(json.dumps(client_info, ensure_ascii=False, indent=2))
    if client_info['name'] != "trackHostUI":
        return

    global current_app
    # 读取缓存的hostIP
    # track_host = current_app.redis_client.get("trackHost")
    # 如果跟客户端发过来的ip不同，就更新缓存的hostIP
    # if track_host is None or track_host != client_info['ip']:
    # if track_host is None:
    # 缓存hostIP
    current_app.redis_client.set("trackHost", client_info['ip'])
    track_host = client_info['ip']
    logger.info(f"发现重要 客户端连接 trackHostUI: {client_info['name']} (IP: {client_info['ip']}) from {from_address}")
    logger.info(f"更新缓存的hostIP: {track_host}")
    publish_msg({
        "event": "video",
        "data": {
            "flv": f"http://{track_host}:8080/flv_stream",
        }
    })


def start_udp_server(app):
    global current_app
    current_app = app
    # 创建并启动UDP发现服务器
    server = UDPDiscoveryServer(
        port=app.config["UDP_PORT"],
        device_name="UDP Server",
        on_client_discovered=on_client_found
    )
    server.start()
